package com.steakliu.gateway.api;
import com.alibaba.fastjson.JSON;
import com.steakliu.gateway.builder.RouteDefinitionBuilder;
import com.steakliu.gateway.definition.GatewayRouteDefinition;
import com.steakliu.gateway.dto.RouteDto;
import com.steakliu.gateway.provider.DynamicRouteProvider;
import com.steakliu.gateway.service.RouteService;
import com.steakliu.gateway.vo.RouteVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/route")
public class RouteApi{
    @Autowired
    private DynamicRouteProvider dynamicRouteProvider;
    @Autowired
    private RouteService routeService;

    @PostMapping("/save")
    public String save(@RequestBody GatewayRouteDefinition gatewayRouteDefinition){
        RouteDefinition definition = RouteDefinitionBuilder.trans(gatewayRouteDefinition);
        return this.dynamicRouteProvider.save(definition);
    }
    @GetMapping("/list")
    public Mono<List<RouteVo>> list(){
        List<RouteDto> list = routeService.list();
        List<RouteVo> listVo = new ArrayList<>();
        for (RouteDto routeDto : list) {
            RouteVo routeVo = new RouteVo();
            routeVo.setRouteId(routeDto.getRouteId())
                    .setRouteName(routeDto.getRouteName())
                    .setCreateName(routeDto.getCreateName())
                    .setCreateTime(routeDto.getCreateTime())
                    .setUpdateName(routeDto.getUpdateName())
                    .setUpdateTime(routeDto.getUpdateTime())
                    .setFilters(JSON.parseObject(routeDto.getFilters()))
                    .setPredicates(JSON.parseObject(routeDto.getPredicates()))
                    .setDelFlag(routeDto.getDelFlag())
                    .setOrder(routeDto.getOrder())
                    .setRemark(routeDto.getRemark())
                    .setUri(routeDto.getUri());
            listVo.add(routeVo);
        }
        return Mono.just(listVo);
    }

}
